import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'pages/page_a.dart';
import 'pages/page_b.dart';

// 原生 -> Flutter 的快捷方式通知
final ValueNotifier<String?> shortcutNotifier = ValueNotifier<String?>(null);

// 定义全局的MethodChannel
const channel = MethodChannel('com.lefushuju.mojiqian');

// 异步调用ArkTS方法（Flutter -> ArkTS）
Future<void> sendToArkTS(dynamic data) async {
  try {
    final response = await channel.invokeMethod('sendToArkTS', data);
    debugPrint('ArkTS响应：$response');
  } on PlatformException catch (e) {
    debugPrint('调用失败：${e.message}');
  }
}

void main() async {
  debugPrint('========== Flutter main() 开始 ==========');
  runApp(const MyApp());
  debugPrint('✓ runApp 执行完成');

  // 监听来自 ArkTS 的调用（这里只负责记录快捷方式，不直接做导航）
  debugPrint('✓ 开始注册 MethodChannel 处理器');
  channel.setMethodCallHandler((MethodCall call) async {
    debugPrint('========== MethodChannel 收到调用 ==========');
    debugPrint('call.method: ${call.method}');
    debugPrint('call.arguments: ${call.arguments}');
    
    if (call.method == 'navigateToPage') {
      final String shortcutKey = call.arguments as String;
      debugPrint('✓ 收到 ArkTS 快捷方式：$shortcutKey');

      // 通知界面层处理导航
      shortcutNotifier.value = shortcutKey;
      debugPrint('✓ 已更新 shortcutNotifier.value = $shortcutKey');
    } else {
      debugPrint('✗ 收到未知的 MethodChannel 调用: ${call.method}');
    }
    debugPrint('========== MethodChannel 调用处理完成 ==========');
  });
  debugPrint('✓ MethodChannel 处理器注册完成');

  // 延迟一下，确保 Flutter UI 完全初始化后再尝试从 ArkTS 获取 want
  debugPrint('✓ 延迟 500ms，等待 Flutter UI 初始化...');
  await Future.delayed(const Duration(milliseconds: 500));
  debugPrint('✓ 延迟完成，开始查询 ArkTS 存储的快捷方式信息');
  
  try {
    // 尝试从 ArkTS 获取存储的 want 信息（如果快捷方式在 Flutter 初始化前被调用）
    debugPrint('✓ 调用 channel.invokeMethod("getWantInfo")');
    final result = await channel.invokeMethod('getWantInfo');
    debugPrint('✓ 收到 ArkTS 返回值: $result');
    
    if (result != null) {
      debugPrint('✓ 从 ArkTS 获取到 want 信息：$result');
      shortcutNotifier.value = result as String;
      debugPrint('✓ 已更新 shortcutNotifier.value = $result');
    } else {
      debugPrint('✗ ArkTS 返回的 want 信息为 null');
    }
  } on PlatformException catch (e) {
    debugPrint('✗ 获取 want 信息失败：${e.message}');
  } catch (e) {
    debugPrint('✗ 获取 want 信息异常：$e');
  }
  debugPrint('========== Flutter main() 结束 ==========');
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    // 监听原生侧发来的快捷方式
    shortcutNotifier.addListener(_onShortcutChanged);
    
    // 关键：检查是否已经有待处理的快捷方式（在监听器添加前就被设置了）
    if (shortcutNotifier.value != null) {
      debugPrint('initState 检测到已有待处理的快捷方式：${shortcutNotifier.value}');
      // 延迟调用，确保 widget 已完全初始化
      Future.microtask(() => _onShortcutChanged());
    }
  }

  void _onShortcutChanged() {
    debugPrint('========== _onShortcutChanged 被触发 ==========');
    final shortcutKey = shortcutNotifier.value;
    debugPrint('shortcutKey: $shortcutKey');
    
    if (shortcutKey == null) {
      debugPrint('✗ shortcutKey 为 null，返回');
      return;
    }
    
    if (!mounted) {
      debugPrint('✗ widget 未挂载，返回');
      return;
    }

    // 用完就清空，避免重复触发
    shortcutNotifier.value = null;
    debugPrint('✓ 已清空 shortcutNotifier.value');

    if (shortcutKey == 'PageA') {
      debugPrint('✓ 准备导航到 PageA');
      Navigator.push(
        context,
        MaterialPageRoute(builder: (_) => const PageA()),
      );
      debugPrint('✓ Navigator.push(PageA) 执行完成');
    } else if (shortcutKey == 'PageB') {
      debugPrint('✓ 准备导航到 PageB');
      Navigator.push(
        context,
        MaterialPageRoute(builder: (_) => const PageB()),
      );
      debugPrint('✓ Navigator.push(PageB) 执行完成');
    } else {
      debugPrint('✗ 未知的 shortcutKey: $shortcutKey');
    }
    debugPrint('========== _onShortcutChanged 结束 ==========');
  }

  @override
  void dispose() {
    shortcutNotifier.removeListener(_onShortcutChanged);
    super.dispose();
  }

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => sendToArkTS(true),
              child: const Text('发送数据到ArkTS'),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const PageA()),
                );
              },
              child: const Text('Go to Page A'),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => const PageB()),
                );
              },
              child: const Text('Go to Page B'),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
